﻿using Common.Device.DeviceDb;
using Common.Device.Enums;
using Common.Device.ViewModels;
using Common.Tool.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace Common.Device.Models
{
    /// <summary>
    /// 测试指令
    /// </summary>
    public class DeviceOrder
    {
        /// <summary>
        /// 使用仪器
        /// </summary>
        public UseDevice Device { get; set; }
        /// <summary>
        /// 测试指令序号
        /// </summary>
        public int index { get; set; }
        /// <summary>
        /// 测试指令编号 abcd...
        /// </summary>
        public string no { get; set; }
        /// <summary>
        /// 测试指令字段名
        /// </summary>
        public string mes { get; set; }
        /// <summary>
        /// 测试指令内容
        /// </summary>
        public Order Order { get; set; }
        /// <summary>
        /// 测试时间
        /// </summary>
        public double time { get; set; }
        /// <summary>
        /// 测试状态
        /// </summary>
        public TestEnum.TestState state { get; set; }
        /// <summary>
        /// 测试结果
        /// </summary>
        public DeviceResult result { get; set; }
        /// <summary>
        /// 测试初始化状态
        /// </summary>
        public void Init()
        {
            time = 0.0;
            state = TestEnum.TestState.等待;
            result = new DeviceResult();
        }
        /// <summary>
        /// 开始测试
        /// </summary>
        /// <param name="testOrder">测试项</param>
        public void Start(TestOrder testOrder)
        {
            result = new DeviceResult();
            state = TestEnum.TestState.测试;
            //时间显示
            DateTime starTime = DateTime.Now;
            DispatcherTimer itemTestTimer = new DispatcherTimer(new TimeSpan(TimeSpan.TicksPerMillisecond * 5), DispatcherPriority.Normal, delegate
            {
                //刷新测试时间
                time = (DateTime.Now - starTime).TotalSeconds;
            }, Application.Current.Dispatcher);
            //测试
            result = DeviceService.DeviceTest(Device, Order, testOrder);
            itemTestTimer.Stop();
            //修改测试状态
            state = result.success? TestEnum.TestState.通过: TestEnum.TestState.失败;
        }
        /// <summary>
        /// 克隆对象
        /// </summary>
        /// <returns></returns>
        public DeviceOrder Clone()
        {
            return new DeviceOrder()
            {
                Device = this.Device,
                index = this.index,
                no = this.no,
                mes = this.mes,
                Order = this.Order.Clone(),
                time = this.time,
                state = this.state,
                result = new DeviceResult(),
            };
        }
    }
}
